package com.xuan.yupao.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuan.yupao.common.DeleteRequest;
import com.xuan.yupao.common.ErrorCode;
import com.xuan.yupao.common.Result;
import com.xuan.yupao.constant.UserConstant;
import com.xuan.yupao.exception.BusinessException;
import com.xuan.yupao.model.domain.Team;
import com.xuan.yupao.model.domain.TeamUser;
import com.xuan.yupao.model.domain.User;
import com.xuan.yupao.model.domain.dto.TeamQuery;
import com.xuan.yupao.model.domain.request.*;
import com.xuan.yupao.model.domain.vo.TeamVo;
import com.xuan.yupao.model.domain.vo.UserVo;
import com.xuan.yupao.service.TeamService;
import com.xuan.yupao.service.TeamUserService;
import com.xuan.yupao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/team")
//@CrossOrigin (origins = "http://localhost:5173", allowCredentials = "true")
public class TeamController {

    @Resource
    private TeamService teamService;

    @Resource
    private UserService userService;

    @Resource
    private TeamUserService teamUserService;

    /**
     *  新增队伍
     * @param teamAddRequest 队伍信息
     * @return  teamId
     */
    @PostMapping("/add")
    public Result<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if (teamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        log.info("[add] teamAddRequest: " + teamAddRequest);

        User loginUser = userService.getLoginUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        boolean result = teamService.addTeam(team, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "新增队伍失败");
        }
        return Result.success(team.getId());
    }

    @PostMapping("/join")
    public Result<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        log.info("[joinTeam] teamJoinRequest: " + teamJoinRequest);

        User loginUser = userService.getLoginUser(request);
        Boolean result = teamService.joinTeam(teamJoinRequest, loginUser);
        return Result.success(result);
    }



    @PostMapping("/delete")
    public Result<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        log.info("[delete] deleteRequest: " + deleteRequest);

        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.deleteTeam(deleteRequest.getId(), loginUser);
        return Result.success(result);
    }

    @PostMapping("/quit")
    public Result<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        log.info("[quitTeam] teamQuitRequest: " + teamQuitRequest);

        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.quitTeam(teamQuitRequest.getTeamId(), loginUser.getId());
        return Result.success(result);
    }

    @PostMapping("/update")
    public Result<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        if (teamUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        log.info("[updateTeam] team: " + teamUpdateRequest);
        User loginUser = userService.getLoginUser(request);

        boolean result = teamService.updateTeam(teamUpdateRequest, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新队伍信息失败");
        }
        return Result.success(true);
    }


    @GetMapping("/{teamId}")
    public Result<TeamVo> getTeamInfoById(@PathVariable(value = "teamId") Long teamId, HttpServletRequest request) {
        if (teamId == null || teamId < 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数非法");
        }
        log.info("[searchTeamById] id: " + teamId);

        List<TeamVo> teamVo = teamService.getTeamInfoById(teamId, userService.getLoginUser(request));

        return Result.success(teamVo.get(0));
    }


    @GetMapping("/list")
    public Result<List<TeamVo>> listTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        log.info("[listTeams] teamQuery: {}", teamQuery);

        // 使用此方式获取用户信息的好处:未登录用户也可以查询
        User loginUser = (User) request.getSession().getAttribute(UserConstant.USER_SESSION);
        boolean isAdmin = userService.isAdmin(loginUser);
        List<Team> teamList = teamService.listTeams(teamQuery, isAdmin);

        // 补充该队伍的队长信息,队伍人数,当前用户(已登录)是否已加入队伍
        List<TeamVo> teamVoList = teamService.addExtraTeamInfo(teamList, loginUser);
        return Result.success(teamVoList);
    }


    @GetMapping("/list/page")
    public Result<List<TeamVo>> listTeamByPage(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        log.info("[listTeamByPage] teamQuery: {}", teamQuery);

        // 使用此方式获取用户信息的好处:未登录用户也可以查询
        User loginUser = (User) request.getSession().getAttribute(UserConstant.USER_SESSION);
        boolean isAdmin = userService.isAdmin(loginUser);
        List<Team> teamList = teamService.listPage(teamQuery, isAdmin);

        // 补充该队伍的队长信息,队伍人数,当前用户(已登录)是否已加入队伍
        List<TeamVo> teamVoList = teamService.addExtraTeamInfo(teamList, loginUser);
        return Result.success(teamVoList);
    }



    @GetMapping("/list/my/create")
    public Result<List<TeamVo>> listTeamsMyCreate(TeamQuery teamQuery, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);

        teamQuery.setUserId(loginUser.getId());
        List<Team> teamList = teamService.listTeamsCreateOrJoin(teamQuery, true);

        // 补充该队伍的队长信息,队伍人数,当前用户(已登录)是否已加入队伍
        List<TeamVo> teamVoList = teamService.addExtraTeamInfo(teamList, loginUser);
        return Result.success(teamVoList);
    }


    @GetMapping("/list/my/join")
    public Result<List<TeamVo>> listTeamsMyJoin(TeamQuery teamQuery, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);

        // team-user表中 user_id = userId
        QueryWrapper<TeamUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginUser.getId());
        List<TeamUser> teamUserList = teamUserService.list(queryWrapper);

        // 对查询出来的数据去重(teamId),防止脏数据出现
        // 此处其实也可以不用去重,因为数据库的 in 条件包含重复值并不影响查询结果
        Map<Long, List<TeamUser>> map = teamUserList.stream().collect(Collectors.groupingBy(TeamUser::getTeamId));
        Set<Long> teamIdSet = map.keySet();
        List<Long> teamIdList = new ArrayList<>(teamIdSet);
        if (CollectionUtils.isEmpty(teamUserList)) {
            return Result.success(new ArrayList<>());
        }
        teamQuery.setIdList(teamIdList);
        List<Team> teamList = teamService.listTeamsCreateOrJoin(teamQuery, true);

        // 补充该队伍的队长信息,队伍人数,当前用户(已登录)是否已加入队伍
        List<TeamVo> teamVoList = teamService.addExtraTeamInfo(teamList, loginUser);
        return Result.success(teamVoList);
    }



    @GetMapping("/member/{teamId}")
    public Result<List<UserVo>> getTeamMemberInfo(@PathVariable(value = "teamId") Long teamId, HttpServletRequest request) {
        if (teamId == null || teamId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginUser = userService.getLoginUser(request);
        List<UserVo> userVoList =  teamService.getTeamMemberInfo(teamId, loginUser.getId());
        return Result.success(userVoList);
    }


    @PostMapping("/kick")
    public Result<Boolean> kickMember(@RequestBody TeamKickMemberRequest kickMemberRequest, HttpServletRequest request) {
        if (kickMemberRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }

        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.kickMember(kickMemberRequest, loginUser);
        return Result.success(result);
    }
}
